package com.yc.grpc;

import com.yc.grpc.host.AbstractGrpcHost;
import com.yc.grpc.proxy.BeanInfo;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.context.ApplicationContext;

import java.lang.reflect.Proxy;


/**
 * @Author: ZhouJianLong
 * @Date: 2024/07/19/14:45
 * @Description:
 */
public class RpcFactoryBean<T>  implements FactoryBean<T> {

    private Class<T> rpcInterface;
    private ApplicationContext applicationContext;

    private AbstractGrpcHost abstractGrpcHost;
    /**
     * spring 上下文
     * @param applicationContext
     */
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public void setAbstractGrpcHost(AbstractGrpcHost abstractGrpcHost) {
        this.abstractGrpcHost = abstractGrpcHost;
    }

    public RpcFactoryBean(){

    }
    public RpcFactoryBean(Class<T> rpcInterface){
        this.rpcInterface = rpcInterface;
    }
    @Override
    public T getObject() throws Exception {
        String beanNamesForType = applicationContext.getBeanNamesForType(rpcInterface)[0];
        BeanInfo beanInfo = new BeanInfo(beanNamesForType,rpcInterface,abstractGrpcHost);
        return (T) Proxy.newProxyInstance(rpcInterface.getClassLoader(),new Class<?>[]{rpcInterface},new RpcInvocationHandler(beanInfo));
    }

    @Override
    public Class<T> getObjectType() {
        return rpcInterface;
    }

    @Override
    public boolean isSingleton() {
        return true;
    }
}
